<?php

namespace app\admin\controller;

use app\admin\model\Files as ModelFiles;
use app\admin\model\Good as ModelGood;
use app\common\LogService;
use Exception;
use think\facade\Db;

class Files extends Base
{
    public function index()
    {
        return view();
    }
    public function list()
    {
        $list = ModelFiles::list();
        return success($list);
    }
    public function del($id)
    {
        $recordLog = function ($status, $message = '') use ($id) {
            LogService::record(
                name: '删除文件',
                target_id: $id,
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: $this->role

            );
        };
        try {
            $data = ModelFiles::find($id);
            $path = app()->getRootPath() . 'public' . $data->getData('file_path');
            if (file_exists($path)) {
                $res = unlink($path);
                if ($res) $recordLog(1);
            }
            ModelFiles::destroy($id);
            return success();
        } catch (Exception $e) {
            $recordLog(0, $e->getMessage());
            return error($e->getMessage());
        }
        $recordLog(0, "文件不存在");
        return error();
    }
    public function delInvalid()
    {
        $recordLog = function ($status, $message = '') {
            LogService::record(
                name: '删除失效文件',
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
                user_type: $this->role

            );
        };
        $list = ModelFiles::select();
        $delId = [];
        try {
            foreach ($list as &$v) {
                if ($v) {
                    $path = app()->getRootPath() . 'public' . $v->getData('file_path');
                    if (!file_exists($path)) {
                        $delId[] = $v->id;
                    }
                }
            }
            $res = ModelFiles::destroy($delId);
            if ($res) return success();
            return error();
        } catch (Exception $e) {
            $recordLog(0, $e->getMessage());
            return error($e->getMessage());
        }
    }
}
